package com.itheima.bos.web.action;

import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.itheima.bos.constant.Constants;
import com.itheima.bos.domain.base.Area;
import com.itheima.bos.domain.take_delivery.Order;
import com.itheima.crm.domain.Customer;

/*
 * 前台系统订单数据处理
 */
@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
@Controller
public class OrderAction extends BaseAction<Order> {

	private String sendAreaInfo;
	private String recAreaInfo;

	public void setRecAreaInfo(String recAreaInfo) {
		this.recAreaInfo = recAreaInfo;
	}

	public void setSendAreaInfo(String sendAreaInfo) {
		this.sendAreaInfo = sendAreaInfo;
	}

	@Action(value = "order_add", results = { @Result(name = "success", type = "redirect", location = "./index.html") })
	public String add() {

		// 封装Area关联
		if(StringUtils.isNoneBlank(sendAreaInfo)){
			Area sendArea = new Area();
			String[] sendAreaInfoStr = sendAreaInfo.split("/");
			sendArea.setProvince(sendAreaInfoStr[0]);
			sendArea.setCity(sendAreaInfoStr[1]);
			sendArea.setDistrict(sendAreaInfoStr[2]);
			model.setSendArea(sendArea);
		}

		if(StringUtils.isNoneBlank(recAreaInfo)){
			Area recArea = new Area();
			String[] recAreaInfoStr = recAreaInfo.split("/");
			recArea.setProvince(recAreaInfoStr[0]);
			recArea.setCity(recAreaInfoStr[1]);
			recArea.setDistrict(recAreaInfoStr[2]);
			model.setRecArea(recArea);
		}


		// 关联当前登录的客户
		Customer customer = (Customer) ServletActionContext.getRequest().getSession().getAttribute("customer");
		model.setCustomer_id(customer.getId());

		// 调用webService保存至bos_managerment中
		WebClient.create(Constants.BOS_MANAGEMENT_URL + "/services/orderService/order").
			type(MediaType.APPLICATION_JSON).post(model);
		return SUCCESS;
	}
}
